package com.bearingnavi.android;

import java.io.File;

import org.apache.log4j.Logger;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings.Secure;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import com.bearingnavi.android.dialogs.Dialog;
import com.bearingnavi.android.listeners.MapLongpressHandler;
import com.bearingnavi.android.services.LocationService;
import com.bearingnavi.android.util.ConfigureLog4J;
import com.bearingnavi.android.util.OverlayResolver;
import com.bearingnavi.android.util.OverlayUtil;
import com.bearingnavi.android.util.Preferences;
import com.bearingnavi.android.util.ReturnNotification;
import com.bearingnavi.android.util.StateSaver;
import com.bearingnavi.android.views.LongpressMapView;
import com.bearingnavi.android.views.LongpressPopupPanel;
import com.bearingnavi.android.views.RotateView;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;

public class BearingNaviActivity extends MapActivity {

	private LocationManager locationManager;
	private LocationService locationListener;
	private MapView mapView;
	
	private SensorManager sensorManager;
	private RotateView rotateView;
	private ConfigureLog4J log4j;
	private Logger log = Logger.getLogger(getClass());
	public static final String appDir = Environment.getExternalStorageDirectory()+"/BearingNavi";
	private NotificationManager mNotificationManager;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		Preferences preferences = Preferences.createInstance(this);
		
		//preferences.setNotRunned(); // for debug only
		if(preferences.getFirstRun()){
			
			preferences.setSendLog(true);
			preferences.setFollowMe(true);
			preferences.setRotateMap(true);
			
			OverlayUtil.about(this);
			preferences.setRunned();
			new File(appDir).mkdirs();
		}
		
		log4j = new ConfigureLog4J();
		log.debug("on-create called");
		
		rotateView = RotateView.createInstance(this);
		
		LayoutInflater inflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
		View mainView = inflator.inflate(R.layout.main, null);
		rotateView.addView(mainView);
		setContentView(rotateView);
		
		mapView = (MapView) findViewById(R.id.map_view);
		mapView.setSatellite(true);
		mapView.getController().setZoom(17);
		
		StateSaver.createInstance(mapView);
		
		locationListener = new LocationService(this, mapView);
		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2500, 12, locationListener);
		mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		((LongpressMapView) mapView).setOnLongpressListener(new MapLongpressHandler(this, mapView));
		
		loadPreData();
		preferences.applyAllSettings();
		
		
		
		// Debug values
//		double lat = 32.063541;
//		double lon = 34.766466;
//		List<GeoPoint> geoPoints = new ArrayList<GeoPoint>();
//		for (int i = 0; i < 1000; i++) {
//			GeoPoint geoPoint = new GeoPoint((int)lat * 1000000, (int)lon * 1000000);
//			geoPoints.add(geoPoint);
//			lat-=0.000002;
//			lon+=0.000002;
//		}
//		locationListener.setLastWalkingGeoPoints(geoPoints);
//		Location location = new Location("");
//		location.setLatitude(lat);
//		location.setLongitude(lon);
//		location.setAltitude(100);
//		location.setBearing(26);
//		locationListener.onLocationChanged(location);
//		RotateView.getInstance().setBearing(10);
	}
	
	private void loadPreData() {
		mapView.getOverlays().addAll(
				OverlayResolver.getOverlays(getIntent().getData(), null, true, mapView));
		OverlayUtil.getAnimateTo(mapView);
		StateSaver.getInstance().marshalOverlays(mapView.getOverlays());
	}

	@Override
	public void onBackPressed() {
		
		if (LongpressPopupPanel.hide(mapView)) {
			return;
		}
		
		if (locationListener.getLastGeoPoint() != null &&
				!locationListener.getLastGeoPoint().equals(mapView.getMapCenter())) {
			
			mapView.getController().animateTo(locationListener.getLastGeoPoint());
			return;
		}
		
		Dialog.buildConfirmDialog(this, getResources().getString(R.string.ExitDLG), new Dialog.ConfirmHandler() {
			
			public void onConfirm() {

				BearingNaviActivity.super.onBackPressed();
			}
		});
	}
	
	@Override
	protected void onDestroy() {
		
		log.debug("on-destroy called");
		mNotificationManager.cancel(1);
		locationManager.removeUpdates(locationListener);
		
		if (Preferences.getInstance().getSendLog()) {
			log4j.uploadLog(Secure.getString(this.getContentResolver(), Secure.ANDROID_ID));
		}
		
		super.onDestroy();
	}
	@Override
	protected void onPause() {
		
		log.debug("on-pause called");
		sensorManager.unregisterListener(locationListener.getSensorService());
		rotateView.disableRotating(false);
		if (isFinishing() == false) // prevent notification when closing app
			 mNotificationManager.notify(1, new ReturnNotification(this));
		
		super.onPause();
	}
	
	@Override
	public void onNewIntent(Intent newIntent) {
		mapView.getOverlays().addAll(
				OverlayResolver.getOverlays(newIntent.getData(), null, false, mapView));
		OverlayUtil.getAnimateTo(mapView);
		StateSaver.getInstance().marshalOverlays(mapView.getOverlays());
		super.onNewIntent(newIntent);
	}
	
	@Override
	protected void onResume() {
		
		log.debug("on-resume called");
		mNotificationManager.cancel(1);
		sensorManager.registerListener(locationListener.getSensorService(), sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_NORMAL);
		
		if (Preferences.getInstance().getRotateMap()) {
			rotateView.enableRotating();
		}
		
		super.onResume();
	}
	@Override
	protected void onStop() {
		
		log.debug("on-stop called");
		super.onStop();
	}
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
		MenuInflater inflater = getMenuInflater();
		
	    inflater.inflate(R.menu.main_menu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	    
	       
	    case R.id.draw_bearing:
			OverlayUtil.drawBearingLine(mapView, this, locationListener, false, null);
	        return true;
	        
	    case R.id.way_point:
	    	OverlayUtil.addWayPoint(mapView, this, locationListener, false, null);
	        return true;
	
	    case R.id.clean:
	    	OverlayUtil.clean(mapView, this);
	        return true;
	        
	    case R.id.settings:
	    	OverlayUtil.settings(this);
	        return true;
	        
	    case R.id.about:
	    	OverlayUtil.about(this);
	        return true;
	        
	        
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	
	
}
